<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>百度URL采集工具</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            padding: 20px;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        .container {
            max-width: 800px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        #logs {
            height: 200px;
            overflow-y: auto;
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 4px;
            font-family: 'Courier New', Courier, monospace;
            font-size: 14px;
        }
        #results {
            height: 300px;
            overflow-y: auto;
        }
        .loading {
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="text-center mb-5">百度URL采集工具</h1>
        
        <form id="collectForm">
            <div class="form-group">
                <label for="keyword" class="form-label">搜索关键字</label>
                <input type="text" id="keyword" class="form-control" placeholder="请输入搜索关键字" required>
            </div>
            
            <div class="form-group">
                <label for="pages" class="form-label">采集页数</label>
                <input type="number" id="pages" class="form-control" min="1" max="100" value="5" required>
            </div>
            
            <div class="form-group">
                <label for="cookie" class="form-label">百度Cookie (可选)</label>
                <input type="text" id="cookie" class="form-control" placeholder="从浏览器复制百度Cookie以绕过验证码限制">
                <small class="form-text text-muted">提示: 不提供Cookie可能导致验证码拦截</small>
            </div>
            
            <div class="d-grid gap-2">
                <button type="submit" class="btn btn-primary btn-lg">开始采集</button>
                <button type="button" id="exportBtn" class="btn btn-secondary" disabled>导出结果</button>
            </div>
        </form>
        
        <div class="mt-5">
            <h4>采集进度</h4>
            <div class="progress mb-3">
                <div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
            </div>
            <div id="logs" class="border rounded"></div>
        </div>
        
        <div class="mt-5">
            <div class="d-flex justify-content-between">
                <h4>采集结果</h4>
                <span id="resultCount" class="badge bg-secondary">0 条</span>
            </div>
            <div id="results" class="border rounded mt-2">
                <div class="text-center text-muted p-5">请点击开始采集按钮开始收集URL</div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const collectForm = document.getElementById('collectForm');
        const logsElement = document.getElementById('logs');
        const resultsElement = document.getElementById('results');
        const progressBar = document.getElementById('progressBar');
        const resultCount = document.getElementById('resultCount');
        const exportBtn = document.getElementById('exportBtn');
        
        let collectedUrls = [];
        
        function addLog(message) {
            const now = new Date().toLocaleTimeString();
            logsElement.innerHTML += `[${now}] ${message}<br>`;
            logsElement.scrollTop = logsElement.scrollHeight;
        }
        
        function clearLogs() {
            logsElement.innerHTML = '';
        }
        
        function updateResults(urls) {
            collectedUrls = urls;
            resultsElement.innerHTML = '';
            
            if (urls.length === 0) {
                resultsElement.innerHTML = '<div class="text-center text-muted p-5">没有采集到URL</div>';
                resultCount.textContent = '0 条';
                exportBtn.disabled = true;
                return;
            }
            
            const table = document.createElement('table');
            table.className = 'table table-hover table-sm';
            table.innerHTML = `
                <thead class="thead-dark">
                    <tr>
                        <th scope="col">序号</th>
                        <th scope="col">URL</th>
                    </tr>
                </thead>
                <tbody></tbody>
            `;
            
            const tbody = table.querySelector('tbody');
            urls.forEach((url, index) => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <th scope="row">${index + 1}</th>
                    <td>
                        <a href="${url}" target="_blank" rel="noopener noreferrer">${url}</a>
                    </td>
                `;
                tbody.appendChild(row);
            });
            
            resultsElement.appendChild(table);
            resultCount.textContent = `${urls.length} 条`;
            exportBtn.disabled = false;
        }
        
        function exportToTxt() {
            if (collectedUrls.length === 0) return;
            
            // 只导出域名，每行一个，不包含序号和引号
            let txtContent = '';
            collectedUrls.forEach((url) => {
                txtContent += `${url}\n`;
            });
            
            const blob = new Blob([txtContent], { type: 'text/plain;charset=utf-8;' });
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.setAttribute('href', url);
            link.setAttribute('download', `百度域名采集结果_${new Date().toISOString().replace(/[:.]/g, '-')}.txt`);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        
        // 当前的SSE连接
        let sseConnection = null;
        
        collectForm.addEventListener('submit', (e) => {
            e.preventDefault();
            
            const keyword = document.getElementById('keyword').value.trim();
            const pages = parseInt(document.getElementById('pages').value) || 1;
            const cookie = document.getElementById('cookie').value.trim();
            
            if (!keyword) {
                alert('请输入搜索关键字');
                return;
            }
            
            if (pages <= 0 || pages > 100) {
                alert('页数必须在1-100之间');
                return;
            }
            
            // 如果已有连接，先关闭
            if (sseConnection) {
                sseConnection.close();
                sseConnection = null;
            }
            
            // 重置状态
            clearLogs();
            updateResults([]);
            progressBar.style.width = '0%';
            progressBar.setAttribute('aria-valuenow', '0');
            exportBtn.disabled = true;
            
            // 启用取消按钮
            const submitButton = collectForm.querySelector('button[type="submit"]');
            submitButton.disabled = false;
            submitButton.textContent = '取消采集';
            
            addLog(`开始采集任务 - 关键字: ${keyword}, 页数: ${pages}`);
            
            // 构建SSE URL
            const url = `/api/UrlCollector/collect?keyword=${encodeURIComponent(keyword)}&pages=${pages}${cookie ? `&cookie=${encodeURIComponent(cookie)}` : ''}`;
            
            // 创建SSE连接
            sseConnection = new EventSource(url);
            
            sseConnection.onmessage = (event) => {
                try {
                    const data = JSON.parse(event.data);
                    
                    // 处理日志更新
                    if (data.log) {
                        addLog(data.log);
                    }
                    
                    // 更新进度
                    if (data.progress !== undefined) {
                        progressBar.style.width = `${data.progress}%`;
                        progressBar.setAttribute('aria-valuenow', data.progress);
                    }
                    
                    // 更新URL结果
                    if (data.urls) {
                        updateResults(data.urls);
                        if (data.urls.length > 0) {
                            exportBtn.disabled = false;
                        }
                    }
                    
                    // 处理错误状态
                    if (data.status === 'error') {
                        addLog(`错误: ${data.message}`);
                        endCollection();
                    }
                    
                    // 处理完成状态
                    if (data.status === 'completed') {
                        addLog('采集任务已完成');
                        endCollection();
                    }
                } catch (error) {
                    addLog(`解析事件数据错误: ${error.message}`);
                }
            };
            
            sseConnection.onerror = (error) => {
                addLog('连接错误，已自动终止');
                endCollection();
            };
            
            // 点击取消按钮时关闭连接
            submitButton.onclick = (e) => {
                e.preventDefault();
                if (confirm('确定要取消采集吗？')) {
                    cancelCollection();
                }
            };
        });
        
        // 结束采集的辅助函数
        function endCollection() {
            if (sseConnection) {
                sseConnection.close();
                sseConnection = null;
            }
            const submitButton = collectForm.querySelector('button[type="submit"]');
            submitButton.textContent = '开始采集';
            submitButton.onclick = null;
        }
        
        // 取消采集
        function cancelCollection() {
            if (sseConnection) {
                sseConnection.close();
                sseConnection = null;
            }
            const submitButton = collectForm.querySelector('button[type="submit"]');
            submitButton.textContent = '开始采集';
            submitButton.onclick = null;
            addLog('采集已取消');
        }
        
        exportBtn.addEventListener('click', exportToTxt);
    </script>
</body>
</html>